import { deleteCart, getCartList, updateCart } from '@/api/cart'
import store from '..'
import { Toast } from 'vant'

export default {
  namespaced: true,
  state () {
    return {
      cartList: []
    }
  },
  data () {
    return {
      time: null
    }
  },
  mutations: {
    setCartList (state, newList) {
      state.cartList = newList
    },
    toggleCheck (state, id) {
      const items = state.cartList.find(item => item.id === id)
      items.isChecked = !items.isChecked
    },
    toggleAllCheck (state, flg) {
      state.cartList.forEach(item => {
        item.isChecked = flg
      })
    },
    changeCount (state, { value, id }) {
      const goods = state.cartList.find(item => item.id === id)
      goods.quantity = value
    }
  },
  actions: {
    async getCartAction (context) {
      const res = await getCartList(store.getters.userId)
      if (res.data === null) {
        res.data = []
      }
      res.data.forEach(element => {
        element.isChecked = true
      })
      context.commit('setCartList', res.data)
    },
    changeCountAction (context, obj) {
      const { value, id } = obj
      context.commit('changeCount', { value, id })
      clearTimeout(this.timer)
      this.timer = setTimeout(async () => {
        await updateCart(value, id)
      }, 2000)
    },
    async delSelect (context) {
      const selCartList = context.getters.selCartList
      const ids = selCartList.map(item => item.id)
      await deleteCart(ids)
      Toast('删除成功')
      context.dispatch('getCartAction')
    }
  },
  getters: {
    cartTotal (state) {
      return state.cartList.reduce((sum, item) => sum + item.quantity, 0)
    },
    selCartList (state) {
      return state.cartList.filter(item => item.isChecked)
    },
    selCount (state, getters) {
      return getters.selCartList.reduce((sum, item) => sum + item.quantity, 0)
    },
    selPrice (state, getters) {
      return getters.selCartList.reduce((sum, item) => {
        return sum + item.price * item.quantity
      }, 0).toFixed(2)
    },
    isAllChecked (state) {
      return state.cartList.every(item => item.isChecked)
    }
  }
}
